//
//  LocalURLCache.m
//  Vgo
//
//  Created by 21CN Vgo on 10-9-7.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LocalURLCache.h"
#import "CmnMacro.h"
#import "NSString+MD5Addition.h"
#import "CmnFunc.h"

@implementation LocalURLCache

@synthesize dataPath;

static LocalURLCache* _sharedLocalURLCache; // self

#pragma mark singleton
- (id)init
{
	if (self = [super init])
	{
		[self initCache];
	}
	
	return self;
}

- (void)dealloc
{
	SAFE_RELEASE(dataPath);
	[super dealloc];
}

+ (LocalURLCache *)sharedLocalURLCache
{
	@synchronized(self)
	{
        if (_sharedLocalURLCache == nil)
		{
            [[self alloc] init]; // assignment not done here
        }
    }
    return _sharedLocalURLCache;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
	{
        if (_sharedLocalURLCache == nil)
		{
            _sharedLocalURLCache = [super allocWithZone:zone];			
            return _sharedLocalURLCache;  // assignment and return on first allocation
        }
    }
	
    return nil; //on subsequent allocation attempts return nil	
}

- (id)copyWithZone:(NSZone *)zone
{
	return self;
}

- (id)retain
{
	return self;
}

- (unsigned)retainCount
{
	return UINT_MAX;  //denotes an object that cannot be released
}

- (oneway void)release
{
	//do nothing
}

- (id)autorelease
{
	return self;
}

- (void)cacheData:(NSData *)theData withURL:(NSURL *)theURL
{
	NSString * filePath = [self cachedFileWithURL:theURL];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
		/* file doesn't exist, so create it */
		[[NSFileManager defaultManager] createFileAtPath:filePath 
												contents:theData 
											  attributes:nil];
	}
}

- (NSData *) cachedDataWithURL:(NSURL *)theURL
{
	NSData *data = nil;
	
	NSString *filePath = [self cachedFileWithURL:theURL];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES)
	{
		data = [NSData dataWithContentsOfFile:filePath];
	}
	return data;
}

- (NSString *)cachedFileWithURL:(NSURL *)theURL
{
	NSString * filePath = [[theURL absoluteString] stringFromMD5];
	filePath = [dataPath stringByAppendingPathComponent:filePath];
	return filePath;
}

- (void) removeCache:(NSURL *)theURL
{
	NSError *error;
	NSString * filePath = [[theURL path] lastPathComponent];
	filePath = [dataPath stringByAppendingPathComponent:filePath];
	[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
}

- (void) initCache
{
	/* create path to cache directory inside the application's Documents directory */
    //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"URLCache"];
	
	NSString *path = [CmnFunc getCachesDirectory];
	self.dataPath = [path stringByAppendingPathComponent:@"URLCache"];
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
	
	NSError *error;
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath 
								   withIntermediateDirectories:NO
													attributes:nil 
														 error:&error]) {
		return;
	}
}


/* removes every file in the cache directory */

- (void) clearCache
{
	NSError *error;
	
	/* remove the cache directory and its contents */
	if (![[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error]) {
		return;
	}
	
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath 
								   withIntermediateDirectories:NO
													attributes:nil 
														 error:&error]) {
		return;
	}
}

@end
